package com.metro.generator.gen;

import com.metro.generator.gen.beans.vo.CodeFileConfig;
import com.metro.utils.FreeMarkerUtil;
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import static com.metro.generator.gen.beans.constant.GenConstant.DEFAULT_ENCODING;

/**
 * Created by xk on 2018/1/29 0029.
 */
public class Generator {

    private static Logger logger = LoggerFactory.getLogger(Generator.class);

    public static Configuration newFreeMarkerConfiguration(File templateRootDir) throws IOException {
        Configuration conf = new Configuration(Configuration.VERSION_2_3_23);

        FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(templateRootDir);
        conf.setTemplateLoader(fileTemplateLoader);
        conf.setNumberFormat("###############");
        conf.setBooleanFormat("true,false");
        conf.setDefaultEncoding(DEFAULT_ENCODING);
//        List<String> autoIncludes = getParentPaths(templateName,"macro.include");
//        List<String> availableAutoInclude = FreemarkerHelper.getAvailableAutoInclude(conf,autoIncludes);
//        conf.setAutoIncludes(availableAutoInclude);
        return conf;
    }

    public static CodeFileConfig buildCodeFileConfig(String genOutRootDir, Map<String, Object> dataMap, File rootDir, File file) {
        CodeFileConfig codeFileConfig = new CodeFileConfig();
        codeFileConfig.setTemplateFile(file);
        String templateName = file.getAbsolutePath().substring(rootDir.getAbsolutePath().length() + 1);
        logger.debug("模板名：{}", templateName);
        codeFileConfig.setTemplateName(templateName);
        String codeFileName = FreeMarkerUtil.renderString(templateName, dataMap);
        File codeFile = new File(genOutRootDir + File.separator + codeFileName);
        File parentDirFile = codeFile.getParentFile();
        if(!parentDirFile.exists()){
            parentDirFile.mkdirs();
        }
        codeFileConfig.setTargetFile(codeFile);
        logger.debug("代码文件配置信息：{}", codeFileConfig);
        return codeFileConfig;
    }
}
